package hw2;

import java.util.HashMap;
import java.util.Iterator;

public class MajorityClassLearner
{
	HashMap<Character, Integer> model;
	
	public MajorityClassLearner()
	{
		model = new HashMap<Character, Integer>();
	}
	
	public void train(String trainingInput)
	{
		int characterIndex = 0;
		while (characterIndex < trainingInput.length())
		{
			char nextCharacter = trainingInput.charAt(characterIndex);
			
			if (model.get(nextCharacter) == null)
				model.put(nextCharacter, 0);
			
			model.put(nextCharacter, model.get(nextCharacter) + 1);
			characterIndex++;
		}
	}
	
	public void test(String testInput)
	{
		int numCorrectPredictions = 0;
		
		int characterIndex = 0;
		while (characterIndex < testInput.length())
		{
			// Predict next character.
			char predictedCharacter = nextPrediction();
			
			// Read character.
			char actualNextCharacter = testInput.charAt(characterIndex);
			
			// Determine if prediction was correct.
			if (predictedCharacter == actualNextCharacter)
				numCorrectPredictions++;
			
			// Update model.
			if (model.get(actualNextCharacter) == null)
				model.put(actualNextCharacter, 0);
			
			model.put(actualNextCharacter, model.get(actualNextCharacter) + 1);
			
			characterIndex++;
		}
		
		// Print percentage of correct predictions.
		System.out.println("Percentage of correct predictions: " + 
				((numCorrectPredictions / (float) testInput.length()) * 100) + "%"); 
		
		// Print random prediction performance (1 / number of unique symbols).
		System.out.println("Random prediction performance: " + 
				(1 / (float) model.keySet().size()) * 100 + "%");
	}
	
	private char nextPrediction()
	{
		int highestFrequency = 0;
		char mostFrequentCharacter = 0;
		
		Iterator<Character> modelIterator = model.keySet().iterator();
		while (modelIterator.hasNext())
		{
			char nextCharacter = modelIterator.next();
			int nextFrequency = model.get(nextCharacter); 
			if (nextFrequency > highestFrequency)
			{
				highestFrequency = nextFrequency;
				mostFrequentCharacter = nextCharacter;
			}
		}
		
		return mostFrequentCharacter;
	}
}
